package xyz.erupt.excel.util;

import org.apache.poi.ss.usermodel.*;

import java.text.DecimalFormat;

public class ExcelUtil {

    public static CellStyle beautifyExcelStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.index);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.index);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.index);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.index);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);
        return style;
    }

    /**
     * 将单元格内容转化为字符串
     *
     * @param cell
     * @return java.lang.String
     * @author Ajian
     * @date 2022-11-16 18:08
     */
    public static String convertCellValueToString(Cell cell) {
        if (null == cell) {
            return null;
        }
        String returnValue = null;
        switch (cell.getCellType()) {
            case STRING:
                returnValue = cell.getStringCellValue();
                break;
            case NUMERIC:
                double numericCellValue = cell.getNumericCellValue();
                boolean isInteger = isIntegerForDouble(numericCellValue);
                if (isInteger) {
                    DecimalFormat df = new DecimalFormat("0");
                    returnValue = df.format(numericCellValue);
                } else {
                    returnValue = Double.toString(numericCellValue);
                }
                break;
            case BOOLEAN:
                boolean booleanCellValue = cell.getBooleanCellValue();
                returnValue = Boolean.toString(booleanCellValue);
                break;
            case BLANK:
                break;
            //公式
            case FORMULA:
                cell.getCellFormula();
                break;
            //故障
            case ERROR:
                break;
            default:
                break;
        }
        return returnValue;
    }

    /**
     * 判断是否为整数，是返回true，否则返回false.
     *
     * @param null
     * @return
     * @author Ajian
     * @date 2022-11-16 18:08
     */
    public static boolean isIntegerForDouble(Double num) {
        double eqs = 1e-10; //精度范围
        return num - Math.floor(num) < eqs;
    }
}
